<template>
  <div>
    <van-nav-bar
      title="黑马头条-登录"
    />
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        required
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[{ validator: mobilerls, required: true, message: '请填写正确的手机号' }]"
      />
      <van-field
        v-model="code"
        required
        type="password"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="[{ validator: coderls, required: true, message: '请填写正确格式的验证码' }]"
      />
      <div style="margin: 16px;">
        <van-button
        round block
        type="info"
        :loading="buttonIsLoding"
        :disabled="buttonIsLoding"
        loading-text="登录中..."
        native-type="submit">
        登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  name: 'HM-Login',
  data () {
    return {
      mobile: '13888888888',
      code: '246810',
      buttonIsLoding: false // 控制按钮是否进入登录状态(true登录中，false登录结束)
    }
  },
  methods: {
    ...mapActions(['loginActions']),
    async onSubmit (values) {
      console.log('submit', values)
      this.buttonIsLoding = true // 按钮开始转圈
      try {
        await this.loginActions(values) // 调用vuex中的actions方法，传递values
        this.$notify({ type: 'success', message: '登录成功' })
        // this.$router.path() 会产生历史记录，可以回退 A -> B -> C
        // this.$router.replace() 直接替换当前页面，无法回退 A -> C
        this.$router.replace('/layout')
      } catch (err) {
        this.$notify({ type: 'danger', message: '登录失败，请检查手机号和验证码是否正确' })
      }
      this.buttonIsLoding = false // 按钮停止转圈
    },
    mobilerls (val) {
      return /^1[3-9]\d{9}$/.test(val)
    },
    coderls (val) {
      return /^\d{6}$/.test(val)
    }
  }
}
</script>

<style scoped>
 /* .van-nav-bar{
  background-color: #007bff;
 }
 ::v-deep .van-nav-bar__title{
  color: white;
 } */
</style>
